package org.grew.openEntity.service.Impl;

import org.grew.openEntity.repository.ProjectRepository;
import org.grew.openEntity.po.logic.ProjectObj;
import org.grew.openEntity.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @program: open_entity
 * @author: todd
 * @create: 2019-01-05 21:49
 * @description: ${description}
 */
@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    @Override
    public Integer createProject(ProjectObj project) {
        int code = 0;
        if(project.getProjectName().isEmpty()){
            return 300;
        }else{
            if(projectRepository.checkProjectName(project.getProjectName()).isPresent())return 400;
            try {
                projectRepository.save(project);
            } catch (Exception e) {
                return 500;
            }
            return 200;
        }
    }

    @Override
    public void updateProject(ProjectObj project) {
        projectRepository.saveAndFlush(project);
    }

    @Override
    public void delProject(Long projectId) {
        projectRepository.deleteById(projectId);
    }

    @Override
    public ProjectObj getProjectById(Long projectId) {
        Optional<ProjectObj> byId = projectRepository.findById(projectId);
        return byId.isPresent()?byId.get():null;
    }

    @Override
    public List<ProjectObj> getProjectByName(String projectName) {
        return projectRepository.findProjectObjByProjectName(projectName);
    }

    @Override
    public long getProjectCount() {
        return projectRepository.count();
    }

    @Override
    public Page<ProjectObj> getPageByProject(int pageIndex, int pageSize) {
        Pageable pageable = new QPageRequest(pageIndex,pageSize);
        return projectRepository.getProjectObjsByPage(pageable);
    }

    @Override
    public List<ProjectObj> getProjectALL() {
        return projectRepository.findAll();
    }
}
